//
//  HLSongBoxViewController.m
//  HLMusicBox
//
//  Created by hulinhu on 2017/12/27.
//  Copyright © 2017年 hulinhu. All rights reserved.
//

#import "HLSongBoxViewController.h"
#import "HLPlayControlView.h"
#import "HLSingViewController.h"
#import "HLTopChannelView.h"
#import "HLSongListTableController.h"
#import <AVFoundation/AVFoundation.h>
#import "MusicPlayerManager.h"
#import <MediaPlayer/MediaPlayer.h>
#import "HLSongItemModel.h"
#import "HLSongListModel.h"
#import <notify.h>


@interface HLSongBoxViewController ()<UIScrollViewDelegate>

@property (nonatomic, strong) HLTopChannelView *topChannelView; // 顶部频道
@property (nonatomic, strong) UIScrollView *contentScrollView; // 中间显示列表
@property (nonatomic, strong) HLPlayControlView *bottomPlayControl; // 底部控制

@property (nonatomic, strong) NSMutableArray *currentChannelsArray; // 频道
@property (nonatomic, strong) MusicPlayerManager *musicPlayer; // 音乐管理器

@property (nonatomic, strong) id playerTimeObserver; // 时间管理器
@property (nonatomic, strong) HLSongItemModel *itemModel;

@property (nonatomic, strong) HLSingViewController *singViewController;

@property (nonatomic, strong) HLSongPlayManager *songPlayManager;    // 单例

@property (nonatomic, strong) UIImageView *lrcImageView;
@property (nonatomic, strong) UIImage * lastImage;//最后一次锁屏之后的歌词海报



@end

@implementation HLSongBoxViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupSubView];
    // ios7 以后得远程控制
    [self createRemoteCommandCenter];

}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self playStateRecover];
}


#pragma mark
#pragma mark - setupSubView
-(void)setupSubView{
    
    self.songPlayManager = [HLSongPlayManager shareInstance];
    self.musicPlayer = [MusicPlayerManager shareInstance];
    
    // 顶部频道
    self.topChannelView = [[HLTopChannelView alloc] initWithFrame:CGRectMake(0, kNavBarHeight+kStatusBarHeight, KScreenWidth, 40)];
    [self.topChannelView.delegateSignal subscribeNext:^(NSNumber *x) {
        [self handleTopChannleView:[x integerValue]];
    }];
    self.topChannelView.channelNameArray = self.currentChannelsArray;
    [self.view addSubview:self.topChannelView];
    
    //详情页
    self.singViewController = [[HLSingViewController alloc] init];
    NSLog(@"self.singViewController  --- %p",self.singViewController );
    
    
    // 添加子VC
    for (NSInteger i = 0; i<self.currentChannelsArray.count; i++) {
        HLSongListTableController *viewController = [[HLSongListTableController alloc] init];
        viewController.channelTitle = self.currentChannelsArray[i];
        [self addChildViewController:viewController];
    }

    // 设置contentScrollView
    [self.view insertSubview:self.contentScrollView atIndex:0];
    [self scrollViewDidEndScrollingAnimation:self.contentScrollView];
    
    // 底部控制条
    self.bottomPlayControl = [[HLPlayControlView alloc] initWithFrame:CGRectMake(0, KScreenHeight*0.92, KScreenWidth, KScreenHeight*0.08) playViewBtnClick:^(NSInteger index) {
        [self handleBtnClick:index];
    }];
    [self.view addSubview:self.bottomPlayControl];
    [self.view bringSubviewToFront:self.bottomPlayControl];
    self.bottomPlayControl.backgroundColor = [UIColor colorWithRed:0.53f green:0.53f blue:0.76f alpha:1.00f];
    
    [self.bottomPlayControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).with.offset(0);
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.width.mas_equalTo(KScreenWidth);
        make.height.mas_equalTo(KScreenHeight*0.08);
    }];
    // 滑动事件
    [[self.bottomPlayControl.songSlider rac_signalForControlEvents:UIControlEventValueChanged] subscribeNext:^(id x) {
        // 更新播放时间
        [self updateTime];
        //如果当前时暂停状态，则自动播放
        if (_musicPlayer.play.rate == 0) {
            self.bottomPlayControl.playAndPauseBtn.image = [UIImage imageNamed:@"cm2_fm_btn_play"];
            [self.bottomPlayControl.playSongImage resumeRotate];
            [_musicPlayer startPlay];
        }
    }];
    
    // 点击事件
    [[self.bottomPlayControl.songSlider rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        // 更新播放时间
        [self updateTime];
        //如果当前时暂停状态，则自动播放
        if (_musicPlayer.play.rate == 0) {
            self.bottomPlayControl.playAndPauseBtn.image = [UIImage imageNamed:@"cm2_fm_btn_play"];
            [self.bottomPlayControl.playSongImage resumeRotate];
            [_musicPlayer startPlay];
        }
        
    }];
    
    // Notification
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(playSongSetting)
                                                 name: @"repeatPlay"
                                               object: nil];
   
    // 播放遇到中断，比如电话进来
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAudioSessionEvent:) name:AVAudioSessionInterruptionNotification object:nil];

    // 监听值变化从新播放 跳过第一次
    [[RACObserve(self.songPlayManager,playSongIndex) ignore:@0] subscribeNext:^(id x) {
        [self playSongSetting];
    }];
}

#pragma mark
#pragma mark - 恢复播放
-(void)playStateRecover {
    [self.bottomPlayControl.playSongImage startRotating];
    if (self.musicPlayer.play.rate == 1) {
        NSLog(@" 播放 ")
        self.bottomPlayControl.playAndPauseBtn.image = [UIImage imageNamed:@"cm2_fm_btn_play"];
        [self.bottomPlayControl.playSongImage resumeRotate];
    }else {
        NSLog(@"停止")
        self.bottomPlayControl.playAndPauseBtn.image = [UIImage imageNamed:@"cm2_fm_btn_pause"];
        [self.bottomPlayControl.playSongImage stopRotating];
    }
}

// 设置播放
-(void)playSongSetting {
    // 获取数据
    self.itemModel = self.songPlayManager.ItemModel;

    // 先移除之前 观察
    if (_playerTimeObserver != nil) {
        [_musicPlayer.play removeTimeObserver:_playerTimeObserver];
        _playerTimeObserver = nil;
        [_musicPlayer.play.currentItem cancelPendingSeeks];
        [_musicPlayer.play.currentItem.asset cancelLoading];
    }
    
    // 设置底部控制信息
    self.bottomPlayControl.playAndPauseBtn.image = [UIImage imageNamed:@"cm2_fm_btn_play"];
    self.bottomPlayControl.songName.text = self.itemModel.songinfo.title;
    self.bottomPlayControl.singerName.text = self.itemModel.songinfo.author;
    [self.bottomPlayControl.playSongImage sd_setImageWithURL:[NSURL URLWithString:self.itemModel.songinfo.pic_small] placeholderImage:nil];
    [self.bottomPlayControl.playSongImage resumeRotate];
    
    // 详情界面设置
    [self.singViewController setSongInforModel:self.itemModel];
    [self.singViewController playStateRecover];

    
    // 播放设置
    [_musicPlayer setPlayItem:self.itemModel.bitrate.file_link];
    [_musicPlayer setPlay];
    [_musicPlayer startPlay];
    
    // 歌词清零
    _songPlayManager.lrcIndex = 0;
    
    // 播放结束通知
   [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(finishedPlaying) name:AVPlayerItemDidPlayToEndTimeNotification object:_musicPlayer.play.currentItem];
    
    // 播放器进度监听
    @weakify(self);
    _playerTimeObserver = [_musicPlayer.play addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        @strongify(self);
        // 当前播放时间
        CGFloat currentTime = CMTimeGetSeconds(time);
        NSLog(@"当前播放时间：%f", currentTime);
        
        // 歌曲总时间
        CMTime total = self.musicPlayer.play.currentItem.duration;
        CGFloat totalTime = CMTimeGetSeconds(total);
        
        // 控制条进度
        self.bottomPlayControl.songSlider.value = (float) ( currentTime / totalTime );
        
        // 详情页的进度
        [self.singViewController setSongPlayCurretTime:currentTime totalTime:totalTime];
        
    
        //监听锁屏状态 lock=1则为锁屏状态
        uint64_t locked;
        __block int token = 0;
        notify_register_dispatch("com.apple.springboard.lockstate",&token,dispatch_get_main_queue(),^(int t){
        });
        notify_get_state(token, &locked);
        
        //监听屏幕点亮状态 screenLight = 1则为变暗关闭状态
        uint64_t screenLight;
        __block int lightToken = 0;
    notify_register_dispatch("com.apple.springboard.hasBlankedScreen",&lightToken,dispatch_get_main_queue(),^(int t){
        });
        notify_get_state(lightToken, &screenLight);
        
        BOOL isShowLyricsPoster = NO;
        if (screenLight == 0 && locked == 1) {
            //点亮且锁屏时
            isShowLyricsPoster = YES;
        }else if(screenLight){
            return;
        }
        
        //展示锁屏歌曲信息，上面监听屏幕锁屏和点亮状态的目的是为了提高效率
        [self showLockScreenTotaltime:totalTime andCurrentTime:currentTime andLyricsPoster:isShowLyricsPoster];
        
        
    }];
}
#pragma mark - 锁屏界面开启和监控远程控制事件
#pragma mark - 锁屏播放设置
//展示锁屏歌曲信息：图片、歌词、进度、演唱者
- (void)showLockScreenTotaltime:(float)totalTime andCurrentTime:(float)currentTime andLyricsPoster:(BOOL)isShow{
    
    NSMutableDictionary * songDict = [[NSMutableDictionary alloc] init];
    //设置歌曲题目
    [songDict setObject: self.itemModel.songinfo.title forKey:MPMediaItemPropertyTitle];
    //设置歌手名
    [songDict setObject:self.itemModel.songinfo.author forKey:MPMediaItemPropertyArtist];
    //设置专辑名
    [songDict setObject:self.itemModel.songinfo.album_title forKey:MPMediaItemPropertyAlbumTitle];
    //设置歌曲时长
    [songDict setObject:[NSNumber numberWithDouble:totalTime]  forKey:MPMediaItemPropertyPlaybackDuration];
    //设置已经播放时长
    [songDict setObject:[NSNumber numberWithDouble:currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    
    
    UIImage * lrcImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.itemModel.songinfo.pic_big]]];

    if (isShow) {
        //制作带歌词的海报
        if (!_lrcImageView) {
            _lrcImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth,KScreenWidth)];
        }
        //主要为了把歌词绘制到图片上，已达到更新歌词的目的
        [_lrcImageView addSubview:self.singViewController.midView.lrcView.lockScreenTableView];
        _lrcImageView.image =lrcImage;
        _lrcImageView.backgroundColor = [UIColor blackColor];
        
        //获取添加了歌词数据的海报图片
        UIGraphicsBeginImageContextWithOptions(_lrcImageView.frame.size, NO, 0.0);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [_lrcImageView.layer renderInContext:context];
        lrcImage = UIGraphicsGetImageFromCurrentImageContext();
        _lastImage = lrcImage;
        UIGraphicsEndImageContext();

    }else{
        if (_lastImage) {
            lrcImage = _lastImage;
        }
    }
    //设置显示的海报图片
    [songDict setObject:[[MPMediaItemArtwork alloc] initWithImage:lrcImage]
                 forKey:MPMediaItemPropertyArtwork];
    
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songDict];
    
}



- (void)createRemoteCommandCenter {
    
    
    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
    commandCenter.playCommand.enabled = YES;
     // 反馈
    // 喜欢
    MPFeedbackCommand *likeCommand = commandCenter.likeCommand;
    likeCommand.enabled = YES;
    likeCommand.localizedTitle = @"喜欢";
    [likeCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"喜欢");
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    //添加不喜欢按钮，这里用作“下一首”
    MPFeedbackCommand *dislikeCommand = commandCenter.dislikeCommand;
    dislikeCommand.enabled = YES;
    dislikeCommand.localizedTitle = @"下一首";
    [dislikeCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"下一首");
        [self nextSongAction];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    //标记
    MPFeedbackCommand *bookmarkCommand = commandCenter.bookmarkCommand;
    bookmarkCommand.enabled = YES;
    bookmarkCommand.localizedTitle = @"标记";
    [bookmarkCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"标记");
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    // 远程控制播放
    [commandCenter.pauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [_musicPlayer.play pause];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    // 远程控制暂停
    [commandCenter.playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [_musicPlayer.play play];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    // 远程控制上一曲
    [commandCenter.previousTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"上一曲");
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    // 远程控制下一曲
    [commandCenter.nextTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"下一曲");
        [self nextSongAction];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    
    //快进
    MPSkipIntervalCommand *skipBackwardIntervalCommand = commandCenter.skipForwardCommand;
    skipBackwardIntervalCommand.preferredIntervals = @[@(10)];
    skipBackwardIntervalCommand.enabled = YES;
    [skipBackwardIntervalCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"你按了快进按键！");
        // 歌曲总时间
        CMTime duration = _musicPlayer.play.currentItem.asset.duration;
        Float64 completeTime = CMTimeGetSeconds(duration);
        // 快进10秒
        self.bottomPlayControl.songSlider.value = self.bottomPlayControl.songSlider.value + 10 / completeTime;
        // 计算快进后当前播放时间
        Float64 currentTime = (Float64)(self.bottomPlayControl.songSlider.value) * completeTime;
        
        // 播放器定位到对应的位置
        CMTime targetTime = CMTimeMake((int64_t)(currentTime), 1);
        [_musicPlayer.play seekToTime:targetTime];
        
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    //在控制台拖动进度条调节进度（仿QQ音乐的效果）
    [commandCenter.changePlaybackPositionCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        CMTime totlaTime = _musicPlayer.play.currentItem.duration;
        MPChangePlaybackPositionCommandEvent * playbackPositionEvent = (MPChangePlaybackPositionCommandEvent *)event;
        [_musicPlayer.play seekToTime:CMTimeMake(totlaTime.value*playbackPositionEvent.positionTime/CMTimeGetSeconds(totlaTime), totlaTime.timescale) completionHandler:^(BOOL finished) {
        }];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    
}


#pragma mark - 歌曲播放结束操作
-(void)finishedPlaying {
    NSLog(@"本歌曲播放结束，准备播放下一首歌曲！");
    [self handleBtnClick:MUSIC_NEXTONE];
}
#pragma mark - 音乐被中断处理
- (void)onAudioSessionEvent: (NSNotification *) notification {
    
    if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) {
        NSLog(@"Interruption notification received!");
        if ([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeBegan]]) {
            NSLog(@"Interruption began!");
            [_musicPlayer stopPlay];
        } else {
            NSLog(@"Interruption ended!");
            [_musicPlayer startPlay];
        }
    }
}

#pragma mark
#pragma mark - handle Click
-(void)handleTopChannleView:(NSInteger)index {
    [self.contentScrollView setContentOffset:CGPointMake(self.contentScrollView.frame.size.width * index, 0) animated:YES];
}

-(void)handleBtnClick:(NSInteger)index {
    
    if (index == MUSIC_DETAIL) {
         [self.navigationController pushViewController:self.singViewController animated:YES];
    }else if (index ==  MUSIC_NEXTONE) {
        [self nextSongAction];
    }else if (index ==  MUSIC_BEGPAUSE) {
        
        if (self.musicPlayer.play.rate == 0) {
            NSLog(@" 播放 ")
            self.bottomPlayControl.playAndPauseBtn.image = [UIImage imageNamed:@"cm2_fm_btn_play"];
            [self.bottomPlayControl.playSongImage resumeRotate];
            [_musicPlayer startPlay];
        }else {
            NSLog(@"停止")
            self.bottomPlayControl.playAndPauseBtn.image = [UIImage imageNamed:@"cm2_fm_btn_pause"];
            [self.bottomPlayControl.playSongImage stopRotating];
            [_musicPlayer stopPlay];
        }
    }
}
-(void)nextSongAction{
    
    NSInteger currentIndex = self.songPlayManager.playSongIndex;
    NSInteger endCountIndex = self.songPlayManager.songListArray.count - 1;
    if (currentIndex < endCountIndex) {
        HLSongListModel*info = self.songPlayManager.songListArray[self.songPlayManager.playSongIndex+1];
        NSLog(@"即将播放下一首歌曲: 《%@》 --- %@", info.title,info.song_id);
        [self.songPlayManager requestCurrentPlaySong:info.song_id playSongIndex:self.songPlayManager.playSongIndex+1];
    } else {
        HLSongListModel *info = self.songPlayManager.songListArray[0];
        NSLog(@"即将播放下一首歌曲: 《%@》", info.title);
        [self.songPlayManager requestCurrentPlaySong:info.song_id playSongIndex:0];
    }
}

#pragma mark
#pragma mark - scrollView delegate
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    
    if (scrollView == self.contentScrollView) {
        NSInteger index = scrollView.contentOffset.x/self.contentScrollView.frame.size.width;
        HLSongListTableController *vc = self.childViewControllers[index];
        vc.view.frame = CGRectMake(scrollView.contentOffset.x, kStatusBarHeight, self.contentScrollView.frame.size.width, self.contentScrollView.frame.size.height);
        vc.tableView.contentInset = UIEdgeInsetsMake(self.topChannelView.height, 0,kTabBarHeight, 0);
        [scrollView addSubview:vc.view];
        for (int i = 0; i<self.contentScrollView.subviews.count; i++) {
            NSInteger currentIndex = vc.tableView.frame.origin.x/self.contentScrollView.frame.size.width;
            if ([self.contentScrollView.subviews[i] isKindOfClass:[UITableView class]]) {
                UITableView *theTableView = self.contentScrollView.subviews[i];
                NSInteger theIndex = theTableView.frame.origin.x/self.contentScrollView.frame.size.width;
                NSInteger gap = theIndex - currentIndex;
                if (gap<=2&&gap>=-2) {
                    continue;
                } else {
                    [theTableView removeFromSuperview];
                }
            }
        }
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.contentScrollView) {
        [self scrollViewDidEndScrollingAnimation:scrollView];
        NSInteger index = scrollView.contentOffset.x/self.contentScrollView.frame.size.width;
        [self.topChannelView selectChannelButtonWithIndex:index];
    }
}


#pragma mark
#pragma mark - 懒加载
-(UIScrollView *)contentScrollView {
    if (!_contentScrollView) {
        _contentScrollView = [[UIScrollView alloc] init];
        _contentScrollView.frame = CGRectMake(0, kNavBarHeight, KScreenWidth, KScreenHeight-self.topChannelView.height-kNavBarHeight);
        _contentScrollView.contentSize = CGSizeMake(KScreenWidth*self.currentChannelsArray.count, 0);
        _contentScrollView.pagingEnabled = YES;
        _contentScrollView.delegate = self;

    }
    return _contentScrollView;
    
}

-(HLSongItemModel *)itemModel {
    
    if (!_itemModel) {
        _itemModel = [[HLSongItemModel alloc] init];
    }
    return _itemModel;
}


// 顶部标题数组设置
-(NSMutableArray *)currentChannelsArray {
    if (!_currentChannelsArray) {
        if (!_currentChannelsArray) {
            _currentChannelsArray = [NSMutableArray arrayWithObjects:@"新歌", @"热歌", @"经典", @"情歌", @"网络", @"影视", @"欧美",@"Bill", @"摇滚", @"爵士", @"流行", nil];
        }
    }
    return _currentChannelsArray;
}

#pragma mark - 更新播放时间
-(void) updateTime {
    
    CMTime duration = _musicPlayer.play.currentItem.asset.duration;
    
    // 歌曲总时间和当前时间
    Float64 completeTime = CMTimeGetSeconds(duration);
    Float64 currentTime = (Float64)(self.bottomPlayControl.songSlider.value) * completeTime;
    
    //播放器定位到对应的位置
    CMTime targetTime = CMTimeMake((int64_t)(currentTime), 1);
    [_musicPlayer.play seekToTime:targetTime];
    
    // 定位歌词位置
    int index = 0;
    for (NSString *indexStr in _songPlayManager.mTimeArray) {
        if ((int)currentTime < [_songPlayManager stringToInt:indexStr]) {
            _songPlayManager.lrcIndex = index;
        } else {
            index = index + 1;
        }
    }
}

#pragma mark - removeObserver
- (void)dealloc{
    [self removeObserver];
}

- (void)removeObserver{
    
    [_musicPlayer.play removeTimeObserver:_playerTimeObserver];
    _playerTimeObserver = nil;

    [_musicPlayer.play.currentItem cancelPendingSeeks];
    [_musicPlayer.play.currentItem.asset cancelLoading];

    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
    [commandCenter.likeCommand removeTarget:self];
    [commandCenter.dislikeCommand removeTarget:self];
    [commandCenter.bookmarkCommand removeTarget:self];
    [commandCenter.nextTrackCommand removeTarget:self];
    [commandCenter.skipForwardCommand removeTarget:self];
    [commandCenter.changePlaybackPositionCommand removeTarget:self];

}


@end
